package com.buka.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("order")
@RefreshScope
public class OrderController {

//    @Value("${className}")
//    public String className;


    @Resource
    RestTemplate restTemplate;

    @Resource
    DiscoveryClient discoveryClient;

    @RequestMapping("toPay")
    public String toPay() {
        List<ServiceInstance> instances = discoveryClient.getInstances("consul-payment");
        ServiceInstance serviceInstance = instances.get(new Random().nextInt(instances.size()));
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url = "http://" + host + ":" + port + "/pay/getInfo";
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    @RequestMapping("toPay2")
    public String toPay2() {
        String servname = "nacos-payment";
        String url = "http://" + servname + "/pay/getInfo";
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }
}
